/*日历插件：
 --------------------*/
function CLT_calendar(option) {
    var oWrap = this.getId(option.wrapId);
    this.days = option.days;
    this.nextUrl = option.nextUrl;      //下一个月的请求链接
    this.preUrl = option.preUrl;        //上一个月的请求链接
    this.month = option.month;
    if (!oWrap) return;
    this.oWrap = oWrap;  //最外层div
    this.oHead = this.getByClassName('g-calendar-hd', this.oWrap)[0];
    this.oBody = this.getByClassName('g-calendar-bd', this.oWrap)[0];  //具体日期div
    this.oTit = this.getByClassName('g-calendar-tit', this.oWrap)[0];
    this.oPrev = this.getByClassName('g-calendar-prev', this.oWrap)[0];  //上一个按钮
    this.oNext = this.getByClassName('g-calendar-next', this.oWrap)[0];  //下一个按钮
    this.init();
}

CLT_calendar.prototype = {

    init: function () {
        this.oTit.innerHTML = '<span>日</span><span>一</span><span>二</span><span>三</span><span>四</span><span>五</span><span>六</span>';
        // 获取今天的日历时间
        var now = new Date();
        if(this.month != null){
            var dtArr = this.month.split("-");
            now = new Date(dtArr[0], parseInt(dtArr[1], 10)-1, dtArr[2]);
        }
        this.c_year = this.year = now.getFullYear();
        this.c_month = this.month = now.getMonth();
        this.date = now.getDate();
        // 初始化--填充日历
        this.fillDate(this.year, this.month);
        //next切换 添加监听
        this.next();
        //prev切换 添加监听
        this.prev();
        this.selected();
    },

    ///////////获取ID元素
    getId: function (id) {
        return document.getElementById(id);
    },

    ////////获取css类名元素
    getByClassName: function (className, parent) {
        var elem = [],
            node = parent != undefined && parent.nodeType == 1 ? parent.getElementsByTagName('*') : document.getElementsByTagName('*'),
            p = new RegExp("(^|\\s)" + className + "(\\s|$)");
        for (var n = 0, i = node.length; n < i; n++) {
            if (p.test(node[n].className)) {
                elem.push(node[n]);
            }
        }
        return elem;
    },

    //填充日历
    fillDate: function (year, month) {
        //本月份第一天是星期几 - 为显示上个月份的天数做铺垫
        var first_day = new Date(year, month, 1).getDay(),
        //如果刚好是星期天，则空出一行（显示上个月的天数）
            first_day = first_day == 0 ? first_day = 7 : first_day;

        //本月份最后一天是几号
        final_date = new Date(year, month + 1, 0).getDate(),
            //上个月的最后一天是几号
            last_date = new Date(year, month, 0).getDate(),
            //剩余的格子数--即排在末尾的格子数
            surplus = 42 - first_day - final_date;


        /*设置表头的日历
         ---------------------------*/
        this.oHead.innerHTML = year + '年' + (month + 1) + '月';
        var div = document.createElement('div');
        var monthStr;
        if(month<9){
            monthStr = "0"+(month+1);
        }else{
            monthStr = month+1;
        }
        div.innerHTML = "<input type='hidden' value='"+year+"-"+monthStr+"-01' name='month' />";
        this.oHead.appendChild(div);
        /*填充日历执行
         ---------------------------*/

        var pre = new Date(year, month, 0);
        var _thisMonth = new Date(year, month + 1, 0);
        var nextMonth = new Date(year, month + 2, 0);

        var lastStr = pre.Format("yyyy-MM-dd");

        var html = '';

        //上个月的显示天数
        for (var i = 0; i < first_day; i++) {
            pre.setDate(last_date - (first_day - 1) + i);
            html += '<span class="g-calendar-grey" data-date='+pre.Format("yyyy-MM-dd")+'>' + (last_date - (first_day - 1) + i) + '</span>';
        }


        if(this.days.length > 0){
            //本月的显示天数
            for (var j = 0; j < final_date; j++) {
                _thisMonth.setDate(j + 1);
                var ht = '<span data-date='+ _thisMonth.Format("yyyy-MM-dd")+'>' + (j + 1) + '</span>';

                for(var h = 0; h < this.days.length; h++){
                    var day = this.days[h];
                    if(day.statutoryDays == _thisMonth.Format("yyyy-MM-dd")){
                        this.days.splice(h, 1);
                        if(day.type == "STATUTORY_HOLIDAYS"){
                            ht = '<span data-date='+ _thisMonth.Format("yyyy-MM-dd")+' class="g-calendar-on-on">' + (j + 1)
                               +'<div><input type="hidden" value="'+ _thisMonth.Format("yyyy-MM-dd")+'" name="date"/></div>'+ '</span>';
                        }
                        if(day.type == "STATUTORY_HOLIDAYS_WORK"){
                            ht = '<span data-date='+ _thisMonth.Format("yyyy-MM-dd")+' class="g-calendar-on-work">' + (j + 1)
                                +'<div><input type="hidden" value="'+ _thisMonth.Format("yyyy-MM-dd")+'" name="date"/></div>'+ '</span>';
                        }
                        break;
                    }
                }
                html += ht;
            }
        }else{
            //本月的显示天数
            for (var j = 0; j < final_date; j++) {
                _thisMonth.setDate(j + 1);
                html += '<span data-date='+ _thisMonth.Format("yyyy-MM-dd")+'>' + (j + 1) + '</span>';
            }
        }


        //下个月的显示天数
        for (var k = 0; k < surplus; k++) {
            nextMonth.setDate(k + 1);
            html += '<span class="g-calendar-grey" data-date='+ nextMonth.Format("yyyy-MM-dd")+'>' + (k + 1) + '</span>';
        }
        //fill
        this.oBody.innerHTML = html;

        // 当前状态 今天日期
        /*if (year == this.c_year && this.c_month == month) {
            this.oBody.getElementsByTagName('span')[first_day + this.date - 1].className = 'g-calendar-on';
        }*/

    },

    //选中事件
    selected:function (){
        var _that = this;
        this.oBody.onclick = function (event){
            var element = event.srcElement;

            if(element.className == "g-calendar-on" || element.className == "g-calendar-on-on" || element.className == "g-calendar-on-work"){
                element.className = '';
                element.children[0].children[0].setAttribute("name", "remove");
            }else{
                element.className = 'g-calendar-on';

                var div = document.createElement('div');
                div.innerHTML = "<input type='hidden' value='"+element.getAttribute('data-date')+"' name='date'/>";
                element.appendChild(div);
            }

        }
    },

    // next切换 下个月
    next: function () {
        var _that = this;
        this.oNext.onclick = function () {
            _that.month++;
            if (_that.month > 11) {
                _that.month = 0;
                _that.year++;
            }
            _that.request(_that.nextUrl);
            // 填充日历
//            _that.fillDate(_that.year, _that.month);
        }

    },

    // prev切换 上个月
    prev: function () {
        var _that = this;
        this.oPrev.onclick = function () {
            _that.month--;
            if (_that.month < 0) {
                _that.month = 11;
                _that.year--;
            }
            _that.request(_that.preUrl);
            // 填充日历
//            _that.fillDate(_that.year, _that.month);
        }

    },

    request: function(url){
        var _that = this;
        var xmlhttp = new XMLHttpRequest();
        var monthStr;
        if(_that.month < 10){
            monthStr = "0"+(_that.month+1);
        }else{
            monthStr = _that.month+1;
        }
        xmlhttp.open("GET", url + "?date="+_that.year+"-"+monthStr+"-01", false);
        xmlhttp.onload = function(data){
            var array = JSON.parse(xmlhttp.response);
            for(var i = 0; i < array.length; i++){
                var d = new Date();
                d.setTime(array[i].statutoryDays);
                array[i].statutoryDays = d.Format("yyyy-MM-dd");
            }
            _that.days = array;
            _that.fillDate(_that.year, _that.month);
        };
        xmlhttp.send();
    }
}